// ReaderRegisterDialog.java - 读者注册对话框
package com.library.gui;

import com.library.entity.Reader;
import com.library.service.AuthService;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ReaderRegisterDialog extends JDialog {
    private AuthService authService;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField emailField;
    private JTextField readerIdField;
    private JTextField nameField;
    private JComboBox<String> genderCombo;
    private JTextField phoneField;
    private JTextField departmentField;
    private JComboBox<String> readerTypeCombo;

    public ReaderRegisterDialog(JFrame parent, AuthService authService) {
        super(parent, "读者账户注册", true);
        this.authService = authService;
        initializeUI();
    }

    private void initializeUI() {
        setSize(500, 550);
        setLocationRelativeTo(getParent());
        setResizable(false);

        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 创建标题
        JLabel titleLabel = new JLabel("读者账户注册", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(new Color(76, 175, 80)); // 绿色主题
        mainPanel.add(titleLabel, BorderLayout.NORTH);

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("账户信息", createAccountInfoPanel());
        tabbedPane.addTab("读者信息", createReaderInfoPanel());

        mainPanel.add(tabbedPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = createButtonPanel();
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private JPanel createAccountInfoPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setBackground(Color.WHITE);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        // 用户名
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("用户名:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        usernameField = new JTextField();
        panel.add(usernameField, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("密码:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        passwordField = new JPasswordField();
        panel.add(passwordField, gbc);

        // 确认密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("确认密码:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        confirmPasswordField = new JPasswordField();
        panel.add(confirmPasswordField, gbc);

        // 邮箱
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("邮箱:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        emailField = new JTextField();
        panel.add(emailField, gbc);

        // 提示信息
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        JLabel hintLabel = new JLabel("<html><font color='gray' size='2'>请牢记您的用户名和密码，用于登录读者自助服务系统。</font></html>");
        panel.add(hintLabel, gbc);

        return panel;
    }

    private JPanel createReaderInfoPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setBackground(Color.WHITE);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        // 读者ID
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("读者ID:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        readerIdField = new JTextField();
        panel.add(readerIdField, gbc);

        // 姓名
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("姓名:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        nameField = new JTextField();
        panel.add(nameField, gbc);

        // 性别
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("性别:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        genderCombo = new JComboBox<>(new String[]{"男", "女"});
        panel.add(genderCombo, gbc);

        // 电话
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("电话:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        phoneField = new JTextField();
        panel.add(phoneField, gbc);

        // 部门/院系
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("部门/院系:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        departmentField = new JTextField();
        panel.add(departmentField, gbc);

        // 读者类型
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.weightx = 0.3;
        panel.add(createRequiredLabel("读者类型:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        readerTypeCombo = new JComboBox<>(new String[]{"学生", "教师", "职工"});
        panel.add(readerTypeCombo, gbc);

        // 提示信息
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        JLabel hintLabel = new JLabel("<html><font color='gray' size='2'>请填写真实的个人信息，这将影响您的借阅权限。</font></html>");
        panel.add(hintLabel, gbc);

        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5));
        panel.setBackground(Color.WHITE);

        JButton registerButton = new JButton("注册读者账户");
        registerButton.setBackground(new Color(76, 175, 80));
        registerButton.setForeground(Color.BLACK);
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        registerButton.setPreferredSize(new Dimension(120, 35));

        JButton cancelButton = new JButton("取消");
        cancelButton.setBackground(new Color(158, 158, 158));
        cancelButton.setForeground(Color.BLACK);
        cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        cancelButton.setPreferredSize(new Dimension(80, 35));

        registerButton.addActionListener(new RegisterAction());
        cancelButton.addActionListener(e -> dispose());

        panel.add(registerButton);
        panel.add(cancelButton);

        return panel;
    }

    private JLabel createRequiredLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        return label;
    }

    private class RegisterAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获取输入数据
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            String email = emailField.getText().trim();
            String readerId = readerIdField.getText().trim();
            String name = nameField.getText().trim();
            String gender = (String) genderCombo.getSelectedItem();
            String phone = phoneField.getText().trim();
            String department = departmentField.getText().trim();
            String readerTypeStr = (String) readerTypeCombo.getSelectedItem();

            // 数据验证
            if (!validateInput(username, password, confirmPassword, email, readerId, name, phone, department)) {
                return;
            }

            // 转换读者类型
            Reader.ReaderType readerType;
            switch (readerTypeStr) {
                case "教师": readerType = Reader.ReaderType.TEACHER; break;
                case "职工": readerType = Reader.ReaderType.STAFF; break;
                default: readerType = Reader.ReaderType.STUDENT;
            }

            // 执行注册
            boolean success = authService.registerReader(username, password, email, 
                                                       readerId, name, gender, phone, 
                                                       department, readerType);

            if (success) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "<html><center><b>读者账户注册成功!</b><br>请使用新账户登录读者自助服务系统。</center></html>", 
                    "注册成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "注册失败，请重试!", "注册失败", JOptionPane.ERROR_MESSAGE);
            }
        }

        private boolean validateInput(String username, String password, String confirmPassword,
                                    String email, String readerId, String name, 
                                    String phone, String department) {
            // 检查必填字段
            if (username.isEmpty() || password.isEmpty() || email.isEmpty() ||
                readerId.isEmpty() || name.isEmpty() || phone.isEmpty() || department.isEmpty()) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "<html><center>请填写所有<b>必填字段</b>!</center></html>", 
                    "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            // 检查密码一致性
            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "两次输入的密码不一致!", "输入错误", JOptionPane.WARNING_MESSAGE);
                confirmPasswordField.setText("");
                confirmPasswordField.requestFocus();
                return false;
            }

            // 检查密码长度
            if (password.length() < 6) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "密码长度不能少于6位!", "输入错误", JOptionPane.WARNING_MESSAGE);
                passwordField.setText("");
                confirmPasswordField.setText("");
                passwordField.requestFocus();
                return false;
            }

            // 检查用户名是否存在
            if (authService.isUsernameExists(username)) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "用户名已存在，请选择其他用户名!", "注册失败", JOptionPane.ERROR_MESSAGE);
                usernameField.requestFocus();
                return false;
            }

            // 简单的邮箱格式验证
            if (!email.contains("@") || !email.contains(".")) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "请输入有效的邮箱地址!", "输入错误", JOptionPane.WARNING_MESSAGE);
                emailField.requestFocus();
                return false;
            }

            // 简单的电话格式验证
            if (!phone.matches("\\d{11}")) {
                JOptionPane.showMessageDialog(ReaderRegisterDialog.this, 
                    "请输入11位手机号码!", "输入错误", JOptionPane.WARNING_MESSAGE);
                phoneField.requestFocus();
                return false;
            }

            return true;
        }
    }
}